package com.xmg.boot.demo.bootlesson1.user.handler.Exception;

import com.xmg.boot.demo.bootcommon.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: ma
 * @date: 2023-12-04
 * @since: 自定义全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger= LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //自定义异常处理
    @ExceptionHandler(value=BaseException.class)
    public Result<Object> baseExceptionHandler(BaseException e){
        logger.error("自定义异常："+e.getMessage());
        return Result.fail(e.getCode(),e.getMessage());
    }

    //空指针异常处理
    @ExceptionHandler(value=NullPointerException.class)
    public Result<Object> nullPointerExceptionHandler(NullPointerException e){
        logger.error("空指针异常："+e);
        return Result.fail(BaseExceptionEnum.BODY_NOT_MATCH.getCode(),BaseExceptionEnum.BODY_NOT_MATCH.getMessage());
    }

    //其他异常处理
    @ExceptionHandler(value=Exception.class)
    public Result<Object> exceptionHandler(Exception e){
        logger.error("其他未知异常："+e.getMessage());
        return Result.fail(BaseExceptionEnum.INTERNAL_SERVER_ERROR.getCode(),BaseExceptionEnum.INTERNAL_SERVER_ERROR.getMessage());
    }
}
